package com.ocom.mqsubsidy.utils;

import com.ocom.mqsubsidy.config.ZkzlMqConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ZkzlProductUitl implements RabbitTemplate.ConfirmCallback{

	private final Logger log = LoggerFactory.getLogger(ZkzlProductUitl.class);
	@Autowired
	private RabbitTemplate rabbitTemplate;

	public void sendMsg(String msg,Integer priority) {
		// 封装消息
		Message message = MessageBuilder.withBody(msg.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
				.setPriority(priority).setContentEncoding("utf-8").setMessageId(msg).build();


		// 构建回调返回的数据
		CorrelationData correlationData = new CorrelationData(msg);
		// 发送消息
		rabbitTemplate.setMandatory(true);
		rabbitTemplate.setConfirmCallback(this);

		// 消息后处理对象,设置一些消息的参数信息
		MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
			@Override
			public Message postProcessMessage(Message message) throws AmqpException {
				//1.设置message的信息
				// 第二个方法：消息的过期时间 ,5秒之后过期   弄23小时过期 TODO
				message.getMessageProperties().setExpiration("82800000");
				//2.返回该消息
				return message;
			}
		};

		rabbitTemplate.setExchange(ZkzlMqConfig.EXCHANGE);

		rabbitTemplate.convertAndSend("routingKeys", message,messagePostProcessor, correlationData);
		log.info("消息发送完成了----------");
	}

	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		String orderId = correlationData.getId(); //id 都是相同的哦  全局ID
        log.info("消息id:{{}}",correlationData.getId());
		if (ack) { //消息发送成功
            log.info("消息发送 确认成功---------------");
		} else {
			//重试机制
			sendMsg(orderId,4);
            log.info("消息发送 确认失败:{{}}",cause);
		}
	}

}
